package test04.sync.test08.t1;

import java.util.LinkedList;

/**
 * @Author lzp
 * @Date 2024-03-22
 */
public class LanZi {

    /**
     *装多个水果的集合
     */
    private LinkedList<Fruit> lanZiList = new LinkedList<>();


    /**
     * 篮子的最大容量
     */
    private static final int LAN_ZI_MAX = 5;


    /**
     *
     * @param name 男孩名
     * @param fruit 摘的水果
     */
    public synchronized void zhai(String name,Fruit fruit){

        if (lanZiList.size() == LAN_ZI_MAX){

            try {
                this.notify();
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }

        lanZiList.add(fruit);
        System.out.println("篮子容量:" + lanZiList.size() + "男孩:" + name + "摘水果" + fruit);


        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public synchronized void chi(String name){

        if (lanZiList.size() == 0){

            try {
                this.notify();
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        Fruit fruit = this.lanZiList.removeLast();
        System.out.println("篮子容量:" + lanZiList.size() + "女孩:" + name + "吃水果" + fruit);

        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

}
